package com.yegs.jltqc.U8ServiceImpl;

import com.yegs.jltqc.TO.InventoryPageQuery;
import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.U8Service.InventoryService;
import com.yegs.jltqc.VO.BaseQuota;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class InventoryServiceImpl implements InventoryService {

    @Autowired
    @Qualifier("u8JdbcTemplate")
    private JdbcTemplate u8JdbcTemplate;


    @Override
    public Page<Map<String, Object>> query(InventoryPageQuery query) {
        String sql = "SELECT TOP " + (query.getPageIndex()) * query.getPageSize()+
                " ROW_NUMBER() OVER(ORDER BY cInvCode ASC) AS ROWID,cInvCode,cInvName,cInvStd from inventory ";
        if(query.getName() != null && query.getName().trim().length() > 0){
            sql += " where cInvName like '%"+query.getName()+"%'";
        }
        if(query.getCode() != null && query.getCode().trim().length() > 0){
            sql += " where cInvCode like '%"+query.getCode()+"%'";
        }
        sql = "select * from ("+sql +") as temp1 where ROWID > " + (query.getPageIndex()-1) * query.getPageSize();
        List<Map<String, Object>> list = u8JdbcTemplate.queryForList(sql);
        sql = "select count (*) from inventory ";
        if(query.getName() != null && query.getName().trim().length() > 0){
            sql += " where cInvName like '%"+query.getName()+"%'";
        }
        if(query.getCode() != null && query.getCode().trim().length() > 0){
            sql += " where cInvCode like '%"+query.getCode()+"%'";
        }
        int total = u8JdbcTemplate.queryForObject(sql,Integer.class);
        PageRequest request = PageRequest.of(query.getPageIndex() -1,query.getPageSize());
        PageImpl page = new PageImpl(list,request,total);
        return page;
    }

}
